/**
 * @fileOverview 游戏手柄类源文件
 * @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
 * @version 0.0.0
 */

(function() {

	/** @exports _Class as Name.Sivory.Castle.Core.Controller */
	var _Class =

	/**
	 * @class 游戏手柄类，将负责监听窗口键盘事件并触发游戏中的操作事件。
	 * @param {Name.Sivory.Castle.Core.Game} game 游戏实例对象，参见{@link Name.Sivory.Castle.Core.Game}
	 * @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
	 * @version 0.0.1
	 */
	Name.Sivory.Castle.Core.Controller = function(g) {

			/**
			 * @private
			 * @field
			 * @type Name.Sivory.Castle.Core.Game
			 * @description 游戏实例引用
			 * @since 0.0.1
			 */
			this.game = g;

			/**
			 * @private
			 * @field
			 * @type Name.Sivory.Castle.Util.HashTable
			 * @description 游戏运行时的键盘状态
			 * @since 0.0.1
			 */
			this.keyboardStatus = new Name.Sivory.Castle.Util.HashTable();

			/**
			 * @private
			 * @field
			 * @type Name.Sivory.Castle.Core.Resource.KeyConfig
			 * @description 游戏按键配置对象
			 * @since 0.0.1
			 */
			this.keyconf = null;

			//初始化
			this.init();

		};

	/**
	 * @private
	 * @function
	 * @description 初始化游戏事件处理
	 * @since 0.0.1
	 */
	_Class.prototype.init = function() {

		var _ins = this;

		var onKeydown = function(e) {
				if(!_ins.keyconf) return;
				var key = _ins.keyconf.keycode(e.keyCode);
				if(key == "unknow") return;
				e.preventDefault();
				var d = new Date();
				if(!game.status.getKeyboardStatus(key)) {
					game.status.setKeyboardStatus(key, d.getTime());
				};
			};

		var onKeyup = function(e) {
				if(!keyconf) return;
				var key = keyconf.keycode(e.keyCode);
				if(key == "unknow") return;
				e.preventDefault();
				game.status.setKeyboardStatus(key, false);
			};

		var onBlur = function(e) {
				e.preventDefault();
				console.log("blur");
				game.status.resetKeyboardStatus();
			};

		window.addEventListener("keydown", onKeydown, false);
		window.addEventListener("keyup", onKeyup, false);
		window.addEventListener("blur", onKeyup, false);
	};

	/**
	 * @public
	 * @function
	 * @description 设置游戏按键信息
	 * @param {Name.Sivory.Castle.Core.Resource.KeyConfig} keys 游戏键位配置对象。
	 * @since 0.0.1
	 */
	_Class.prototype.setKeys = function(keys) {
		this.keyconf = k;
	};

	/**
	 * @private
	 * @function
	 * @description 游戏事件托管
	 * @param {String} key 设置key键已被按下
	 * @since 0.0.1
	 */
	_Class.prototype.getKeyboardStatus = function(key) {
		if(keyboardStatus.containsKey(key)) {
			return keyboardStatus.get(key);
		} else {
			return false;
		}
	};

})();